//
// Created by skynet on 2020/5/25.
//

#include "Hello.h"

/**
 * 普通测试方法
 * @return
 */
int Hello::hello() {
    return 100;
}

/**
 * 调用activity的普通方法
 * @param pEnv
 * @param obj
 * @return
 */
int Hello::callObjectMethod(JNIEnv *env, jobject obj) {
    jclass findClass = env->FindClass("com/tensor/skynet/MainActivity");
     //获取方法printDescription 方法id，
    jmethodID methodID = env->GetMethodID(findClass, "hello", "()V");
    env->CallVoidMethod(obj, methodID);
    //创建构建器 , AAudio 音频流通过该构建器创建
    return 0;
}
/**
 * 调用java类的实例方法
 * @param env
 * @param obj
 * @return
 */
jstring Hello::callJavaHello(JNIEnv *env, jobject obj) {
    //找到相关的类 注意路径是带反斜杆  不是带.
    jclass cls_First = env->FindClass("com/tensor/skynet/jni/JNIUtils");
//    cls_First=env->GetObjectClass(obj);
    if(cls_First == NULL){
        return NULL;
    }
    //找到对应的方法
    jmethodID mtd_method = env->GetMethodID(cls_First,"hello",
                                            "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
    if(mtd_method == NULL){
        return NULL;
    }
    //找到对应的构造方法
    jmethodID mtd_construct = env->GetMethodID(cls_First,"<init>","(Ljava/lang/String;)V");
    if(mtd_construct == NULL){
        return NULL;
    }
    jfieldID fld_address = env->GetFieldID(cls_First,"addRess","Ljava/lang/String;");
    jfieldID jfieldId_static= env->GetStaticFieldID(cls_First,"name","Ljava/lang/String;");
    if(fld_address == NULL){
        return NULL;
    }
    jstring address = env->NewStringUTF("shanghai");
    if(address == NULL){
        return NULL;
    }
    //创建相应的对象
    jobject oFirst = env->NewObject(cls_First,mtd_construct,env->NewStringUTF("kunming"));
    if(oFirst == NULL){
        return NULL;
    }
    //注意此时的对象  应该是jobject对象 非jclass对象
//    env->SetObjectField(oFirst,fld_address,address);
    jstring message = env->NewStringUTF("call method ");
    //调用java层实例方法  注意此时的对象  应该是jobject对象 非jclass对象
    jstring result = static_cast<jstring>(env->CallObjectMethod(oFirst, mtd_method,env->GetStaticObjectField(cls_First,jfieldId_static),
                                                                env->GetObjectField(oFirst,fld_address)));
    //清除对象的引用
    env->DeleteLocalRef(message);
    env->DeleteLocalRef(cls_First);
    env->DeleteLocalRef(oFirst);
    env->DeleteLocalRef(address);
    return result;
}

/**
 * 调用java类的静态方法
 * @param env
 * @param obj
 * @return
 */
jstring Hello::callJavaStaticMethod(JNIEnv *env, jobject obj) {
    jclass findClass = env->FindClass("com/tensor/skynet/jni/JNIUtils");
    // 获取方法printDescription 方法id，
    jmethodID methodID = env->GetStaticMethodID(findClass, "staticMethod", "(Ljava/lang/String;)Ljava/lang/String;");
    jstring result = static_cast<jstring>(env->CallStaticObjectMethod(findClass, methodID, env->NewStringUTF("kkkk")));
    return result;
}
